﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Utils.Common
{
    public static class SoftSecurity
    {

        public static readonly string Password = "zxcvBNMM";
        internal static string MD5Encrypt(string pToEncrypt)
        {
            return SoftSecurity.MD5Encrypt(pToEncrypt, Password);
        }

        public static string MD5Encrypt(string pToEncrypt, string Password)
        {
            string s = Password;
            DESCryptoServiceProvider cryptoServiceProvider = new DESCryptoServiceProvider();
            byte[] bytes = Encoding.Default.GetBytes(pToEncrypt);
            cryptoServiceProvider.Key = Encoding.ASCII.GetBytes(s);
            cryptoServiceProvider.IV = Encoding.ASCII.GetBytes(s);
            MemoryStream memoryStream = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, cryptoServiceProvider.CreateEncryptor(), CryptoStreamMode.Write);
            cryptoStream.Write(bytes, 0, bytes.Length);
            cryptoStream.FlushFinalBlock();
            StringBuilder stringBuilder = new StringBuilder();
            foreach (byte num in memoryStream.ToArray())
                stringBuilder.AppendFormat("{0:X2}", (object)num);
            stringBuilder.ToString();
            return stringBuilder.ToString();
        }

        internal static string MD5Decrypt(string pToDecrypt)
        {
            return SoftSecurity.MD5Decrypt(pToDecrypt, Password);
        }

        public static string MD5Decrypt(string pToDecrypt, string password)
        {
            if (pToDecrypt == "")
                return pToDecrypt;
            string s = password;
            DESCryptoServiceProvider cryptoServiceProvider = new DESCryptoServiceProvider();
            byte[] buffer = new byte[pToDecrypt.Length / 2];
            for (int index = 0; index < pToDecrypt.Length / 2; ++index)
            {
                int int32 = Convert.ToInt32(pToDecrypt.Substring(index * 2, 2), 16);
                buffer[index] = (byte)int32;
            }
            cryptoServiceProvider.Key = Encoding.ASCII.GetBytes(s);
            cryptoServiceProvider.IV = Encoding.ASCII.GetBytes(s);
            MemoryStream memoryStream = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, cryptoServiceProvider.CreateDecryptor(), CryptoStreamMode.Write);
            cryptoStream.Write(buffer, 0, buffer.Length);
            cryptoStream.FlushFinalBlock();
            cryptoStream.Dispose();
            return Encoding.Default.GetString(memoryStream.ToArray());
        }
    }
}
